#!/usr/bin/ruby

require 'socket'		# Sockets are in standard library
require 'thread'		# This is imported so the sending and recieving of messages could be simultanious


class Client
	def start()		# Use this method to puts some welcome message to the client locally if desired							
	pickHost()		# Move on to the next method to pick a server
	end

	def pickHost()							# This method is for the user to define the server they want to connect to
		puts "Which server would you like to connect to?"
		print ">"
		hostname = STDIN.gets.chomp
		#confirm the host in online (I have yet to do this)
		pickName(hostname)
	end

	def pickName(hostname)						# This method is for the user to set the nick name they want to use
		puts "What is your preferred name"
		print ">"
		name = STDIN.gets.chomp
		#make sure name isn't empty (I have yet to do this, just going to make a statement to confirm name != ""
		connect(hostname, name)	
	end

	def connect(hostname, name)					# This method opens the socket and sends the server the nick name,
		s = TCPSocket.open(hostname, 2000)			# then starts the threads to listen and send messages using the 
		s.puts name						# startThreads method.
		startThreads(s)
	end

	def send(s)				# This is the method that forever allows the user to type something in and send it to the server
		loop{
			s.puts STDIN.gets.chomp
		}
	end

	def recieve(s)				# This method will print anything the server sends to it when it recieves it
		loop{	
			puts s.gets
		}
	end

	def startThreads(s)				# This method is used to multi thread the sender and reciever methods
		sender = Thread.new{send(s)}
		reciever = Thread.new{recieve(s)}
		sender.join	# This starts the method for sending messages as a new thread
		reciever.join	# This starts the method for recieving messgae as a new thread
	end

end

run = Client.new
run.start
